﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnitDriven;
using Windows.ApplicationModel.DataTransfer;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

namespace UnitDrivenRT
{
    public sealed partial class TestEngine : Page
    {
        private TestContext _context;
        public TestContext Context
        {
            get { return _context; }
        }

        public TestEngine()
        {
            this.InitializeComponent();
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            this.DataContext = this._context = (TestContext)e.Parameter;
            base.OnNavigatedTo(e);
        }

        private void RunAll_Click(object sender, RoutedEventArgs e)
        {
            this.Focus(FocusState.Programmatic);
            _context.Run();
        }

        private void Run_Click(object sender, RoutedEventArgs e)
        {
            Button b = (Button)sender;
            var tester = (IRunTests)b.DataContext;
            tester.RunTests();
        }

        private void SummaryCopy_Click(object sender, RoutedEventArgs e)
        {
            var summary = this._context.ToSummary();
            if (System.Diagnostics.Debugger.IsAttached)
            {
                System.Diagnostics.Debugger.Break();
                System.Diagnostics.Debug.WriteLine(summary);
            }
            var data = new DataPackage();
            data.SetText(summary);
            Clipboard.SetContent(data);
        }

        private void ErrorDetails_Click(object sender, RoutedEventArgs e)
        {
            Button b = (Button)sender;
            var tester = (IRunTests)b.DataContext;
            ((Frame)Window.Current.Content).Navigate(typeof(ErrorDetails), new ErrorDetailsModel
            {
                Test = tester,
                Context = this._context
            });
        }

        private void TextBox_GotFocus(object sender, RoutedEventArgs e)
        {
            this.filterText.SelectAll();
        }

        private void TextBox_KeyUp(object sender, KeyRoutedEventArgs e)
        {
            switch (e.Key)
            {
                case Windows.System.VirtualKey.Enter:
                case Windows.System.VirtualKey.Accept:
                    {
                        this.Context.Filter = this.filterText.Text;
                        this.filterText.SelectAll();
                    }
                    break;
            }
        }
    }
}
